package controllers;

import java.util.List;

import controllers.Security;

import models.Comment;
import models.Course;
import models.Lecture;
import models.Question;
import models.User;
import play.data.validation.Required;
import play.mvc.*;

@With(Secure.class)
public class Questions extends Controller {

    public static void index() {
    	User user = Security.getConnected();
    	List questions = Question.find("answered = false order by postedAt desc").fetch();
        render(user, questions);
    }
    
    public static void show(Long questionId) {
    	User user = Security.getConnected();
    	Question question = Question.findById(questionId);
    	Lecture lecture = question.lecture;
    	List comments = Comment.find("question = ? order by postedAt desc", question).fetch();
    	render(user, question, lecture, comments);
    }
    
    public static void addComment(Long questionId, @Required String content) throws Throwable {
    	Question question = Question.findById(questionId);
    	User user = Security.getConnected();
    	question.comment(user, content);
    	show(questionId);
    }
    
    public static void deleteComment(Long questionId, Long commentId) {
    	User user = Security.getConnected();
    	Comment comment = Comment.findById(commentId);
    	
    	if (comment.postedBy == user)
    		comment.delete();
    	show(questionId);
    }
    
    public static void voteOnQuestion(Long questionId) {
    	User user = Security.getConnected();
    	if (Security.connectedUserIsPremium()) {
	    	Question question = Question.findById(questionId);
	    	user.voteOnQuestion(question);
    	}
    	show(questionId);
    }
    
    public static void unvoteQuestion(Long questionId) {
    	User user = Security.getConnected();
    	Question question = Question.findById(questionId);
    	user.unvoteQuestion(question);
    	show(questionId);
    }

}
